package com.apartment.control;

import com.alibaba.fastjson.JSONObject;
import com.apartment.data.entity.Apartment;
import com.apartment.data.entity.Landlord;
import com.apartment.data.entity.User;
import com.apartment.sevice.ApartmentService;
import com.apartment.sevice.LandlordService;
import com.apartment.sevice.UserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.thymeleaf.TemplateEngine;

import java.io.File;
import java.io.FileOutputStream;
import java.util.List;

/**
 * Author : xuzhiyong
 * Date : 2022/5/30 22:28
 */
@Controller
@RequestMapping("/landlord")
public class LandlordController {
    @Autowired
    private ApartmentService apartmentService;

    @Autowired
    private UserService userService;

    @Autowired
    private LandlordService landlordService;

    @RequestMapping("/exit")
    public String ex(){
        return "redirect:/landlord/toLogin";
    }

    @RequestMapping("/toLogin")
    public String toLogin(){
        return "landlord/landlordLogin";
    }

    @RequestMapping("/login")
    public String login(Model model, String username,String password){
        System.out.println(username+password);
        Landlord landlord = landlordService.findLandlordByUsername(username);
        model.addAttribute("landlord",landlord);
        if (landlordService.landlordLogin(username,password)!=null){
            return "landlord/landlordIndex";
        }else
            return "error";
    }

    @RequestMapping("/landlordHomePage")
    public String landlordHome(Model model,String username){
        Landlord landlord = landlordService.findLandlordByUsername(username);
        model.addAttribute("landlord",landlord);
        return "landlord/landlordHomePage";
    }

    @RequestMapping("/apartmentListForLandlordId")
    public String apartmentListForLandlordId(Model model,String id){
        List<Apartment> apartments = apartmentService.findApartmentByLandlordId(id);
        model.addAttribute("apartment",apartments);
        return "apartment/apartmentListForLandlord";
    }

    @RequestMapping("/toAddApartment")
    public String toAdd(){
        return "apartment/addApartment";
    }

    @RequestMapping("addApartment")
    public String addApartment(Apartment apartment){
        apartmentService.addApartment(apartment);
        return "redirect:/apartment/apartmentList";
    }

    @RequestMapping("/apartmentList")
    public String findAllApartment(Model model){
        System.out.println("查询所有公寓");
        List<Apartment> apartments = apartmentService.findAllApartment();
        model.addAttribute("apartments",apartments);
        return "apartment/apartmentList";
    }

    @RequestMapping("/apartmentListForUser")
    public String findAllApartmentForUser(Model model,String username){
        User user = userService.findUserByUsername(username);
        model.addAttribute("user",user);
        List<Apartment> apartments = apartmentService.findAllApartment();
        model.addAttribute("apartments",apartments);
        return "apartment/apartmentListForUser";
    }

    @RequestMapping("/apartmentDetail")
    public String findApartmentById(Model model,Integer id,String username){
        User user = userService.findUserByUsername(username);
        model.addAttribute("user",user);
        Apartment apartment = apartmentService.findApartmentById(id);
        model.addAttribute("apartment",apartment);
        return "apartment/apartmentDetail";
    }



    /**
     * 文件上传
     * @param file
     * @param filePath
     * @param fileName
     * @throws Exception
     */
    public static void uploadFile(byte[] file,String filePath,String fileName)throws Exception{
        File targetFile = new File(filePath);//给出路径进行操作
        if (targetFile.exists()){//判断是否存在
            targetFile.mkdirs();//不存在，自动创建
        }
        //字符输出流，向文件写入
        //定位文件
        FileOutputStream fileOutputStream = new FileOutputStream(filePath+"/"+fileName);
        fileOutputStream.write(file);
        fileOutputStream.flush();
        fileOutputStream.close();
    }
    @RequestMapping(value="/upload",method = RequestMethod.POST)
    @ResponseBody
    public JSONObject upload(@RequestParam("file") MultipartFile file, Model model){
        System.out.println(file);
        JSONObject jsonObject = new JSONObject();
        //文件名称            1970到现在的毫秒数           文件名称
        String fileName = System.currentTimeMillis()+file.getOriginalFilename();
        //文件绝对路径
        String filePath = "E:/JSP/Wokespace/apartmentRent/untitled/apartmentRent/src/main/resources/static/images/";
        if (jsonObject.isEmpty()){//判断是否上传
            jsonObject.put("success","0");//失败输出0
            jsonObject.put("fileName","");
        }
        try {
            //调用定义的方法，进行操作
            uploadFile(file.getBytes(),filePath,fileName);
            jsonObject.put("success",1);
            jsonObject.put("fileName",fileName);
            jsonObject.put("xfileName","/images/"+fileName);

        } catch (Exception e) {
            e.printStackTrace();
        }
        model.addAttribute("xfileName",filePath+fileName);
        return jsonObject;
    }


    @RequestMapping("/toForgetPassword")
    public String toforget(){
        return "user/userForgetPassword";
    }

    private static Logger LOG= LoggerFactory.getLogger(UserController.class);

    @Value("${spring.mail.username}")
    private String Mail;

    @Autowired
    private JavaMailSender mailSender;

    @Autowired
    private TemplateEngine templateEngine;

    @PostMapping("/forgetPassword")
    @ResponseBody
    public String sendMail(@RequestParam("mail") String mail){
        Landlord landlord = landlordService.findLandlordByMail(mail);
        if(landlord !=null){
            String code = landlord.getPassword();
            SimpleMailMessage message = new SimpleMailMessage();
            message.setFrom(Mail);
            message.setTo(mail);
            message.setSubject("你的密码");
            message.setText("密码为："+code);
            mailSender.send(message);
            System.out.println(message);
            LOG.info("发送成功！！！");
            return code;
        }else {
            String code = "";
            return code;
        }
    }

}
